﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleConfigurator.Model;
using VehicleConfigurator.Database;
using log4net;

namespace VehicleConfigurator
{
    public partial class FrmMakeModelEditioncs : Form
    {
        readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Constructing log

        //longdq
        //user function

        public void LoadDataMake()
        {
            string sql = "SELECT * FROM make ORDER BY NAME ";
            clsDb db = new clsDb();
            db.LoadData(sql, this.dgvMake);


        }
        public void UpdateData(string table, DataGridView dg)
        {
            clsDb db = new clsDb();
            db.updateData(table, dg);

            //if (table.ToLower().Equals("make"))
            //    this.LoadDataMake();


        }


        //models grid

        public void LoadDependentGrids(string id, string table, string key, DataGridView dg)
        {
            string sql = "SELECT * FROM {0} WHERE {1} in ({2}) ORDER BY NAME ";
            sql = String.Format(sql, table, key, id);
            clsDb db = new clsDb();
            db.LoadData(sql, dg);

        }

        void ReFormatGrid()
        {
            dgvMake.AllowUserToAddRows = false;
            dgvMake.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvMake.ScrollBars = ScrollBars.Both;

            dgvModel.AllowUserToAddRows = false;
            dgvModel.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvModel.ScrollBars = ScrollBars.Both;

            dgvEdition.AllowUserToAddRows = false;
            dgvEdition.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvEdition.ScrollBars = ScrollBars.Both;

            dgvOptionGroup.AllowUserToAddRows = false;
            dgvOptionGroup.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvOptionGroup.ScrollBars = ScrollBars.Both;

            dgvModelYears.AllowUserToAddRows = false;
            dgvModelYears.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvModelYears.ScrollBars = ScrollBars.Both;
        }

        //void FirstLoadGrid()
        //{
        //    string id = dgvMake.Rows[0].Cells[0].Value.ToString();
        //    //load Modelgrid
        //    this.LoadDependentGrids(id,"model",this.dgvModel);
        //}
        void LoadDataCombo()
        {
            if (this.dgvMake.Rows.Count >0)
            {
                DataGridViewComboBoxColumn comboCol = (DataGridViewComboBoxColumn)this.dgvModel.Columns["MakeOID"];
                DataTable ds = (DataTable)this.dgvMake.DataSource;
                comboCol.DataSource = ds;
                comboCol.ValueMember = "OID";
                comboCol.DisplayMember = "Name";

                //modelyear
                DataGridViewComboBoxColumn comboColYear = (DataGridViewComboBoxColumn)this.dgvModelYears.Columns["ModelYearMakeOID"];
                comboColYear.DataSource = ds;
                comboColYear.ValueMember = "OID";
                comboColYear.DisplayMember = "Name";

                //OptionGroup
                DataGridViewComboBoxColumn comboColOption = (DataGridViewComboBoxColumn)this.dgvOptionGroup.Columns["OptionGroupMakeOID"];
                comboColOption.DataSource = ds;
                comboColOption.ValueMember = "OID";
                comboColOption.DisplayMember = "Name";

                //modelEdition
                clsDb db = new clsDb();
                DataTable dt = new DataTable();
                string sql = "select * from Model";
                dt = db.GetDataTable(sql);
                if (dt != null)
                {
                    DataGridViewComboBoxColumn comboColEdition = new DataGridViewComboBoxColumn();
                    comboColEdition = (DataGridViewComboBoxColumn)this.dgvEdition.Columns["ModelEditionModelOID"];
                    comboColEdition.DataSource = dt;
                    comboColEdition.ValueMember = "OID";
                    comboColEdition.DisplayMember = "Name";
                }
                
            }
        }

        private bool isMakeUsed(string table, string id, string countField)
        {
            bool val = false;

            string sql = "Select count({0}) from {1} where {0} in ({2})";
            sql = String.Format(sql, countField, table, id);
            int count = 0;
            clsDb db = new clsDb();
            count = db.countRecord(sql);
            if (count > 0)
                val = true;
            else
                val = false;
            return val;
        }



        //-----------------------Control Event-------------------------------------------
        //


        public FrmMakeModelEditioncs()
        {
            InitializeComponent();
        }

        private void btClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmMakeModelEditioncs_Load(object sender, EventArgs e)
        {
            this.ReFormatGrid();
            this.LoadDataMake();
            if (this.dgvMake.Rows.Count > 0)
            {
                dgvMake.Rows[0].Selected = true;
                this.LoadDataCombo();
                //this.FirstLoadGrid();
            }


           
        }

        private void btnMakeNew_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)dgvMake.DataSource;
                dt.Rows.Add(-1, "Name");
                dgvMake.DataSource = dt;
                ScrollToBottom(dgvMake);
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }

        }

        private void bntSave_Click(object sender, EventArgs e)
        {
            try
            {
                
                    this.UpdateData("make", this.dgvMake);
                    this.LoadDataMake();
                    this.LoadDataCombo();

                
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message) ;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            
            try
            {
                List<DataGridViewRow> list = new List<DataGridViewRow>();
                foreach (DataGridViewRow item in this.dgvMake.SelectedRows)
                {
                    if (!this.isMakeUsed("model", item.Cells["OID"].Value.ToString(), "makeOID")
                        && !this.isMakeUsed("modelyear", item.Cells["OID"].Value.ToString(), "MakeOID")
                        && !this.isMakeUsed("optiongroup", item.Cells["OID"].Value.ToString(), "makeOID"))//check Make is used?
                        dgvMake.Rows.RemoveAt(item.Index);
                    else
                        list.Add(item);
                }
                string name = "";
                if (list.Count > 0)
                {
                    foreach (DataGridViewRow r in list)
                    {
                        name += r.Cells["MakeName"].Value.ToString() + " , ";
                    }
                    if (!String.IsNullOrEmpty(name))
                        name = name.Remove(name.LastIndexOf(","));
                    MessageBox.Show(String.Format("Items were used : {0}.", name));

                }
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }

        }

        private void dgvMake_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.dgvMake.SelectedRows.Count>0)
                {
                    string id = "";
                    foreach (DataGridViewRow item in this.dgvMake.SelectedRows)
                    {
                        if (id.Equals(""))
                            id += item.Cells["OID"].Value.ToString();
                        else
                            id += " , " + item.Cells["OID"].Value.ToString();

                    }

                    //log.Debug("ID----: " + id.ToString());
                    if (!String.IsNullOrEmpty(id))
                    {
                        //clear other 
                        this.dgvModel.DataSource = null;
                        this.dgvModelYears.DataSource = null;
                        this.dgvOptionGroup.DataSource = null;
                        this.dgvEdition.DataSource = null;
                        //load modelGrid
                        this.LoadDependentGrids(id, "model", "makeOID", this.dgvModel);
                        if (dgvModel.Rows.Count > 0)
                            dgvModel.Rows[0].Selected = true;
                        //load ModelYearGrid
                        this.LoadDependentGrids(id, "modelyear", "makeOID", this.dgvModelYears);
                        if (dgvModelYears.Rows.Count > 0)
                            dgvModelYears.Rows[0].Selected = true;
                        //load ModelGrid
                        this.LoadDependentGrids(id, "optiongroup", "makeOID", this.dgvOptionGroup);
                    } 
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message) ;
            }


        }

        private void bntModelNew_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)dgvModel.DataSource;
                string val = "";
                val = this.dgvMake.SelectedRows[0].Cells["OID"].Value.ToString();
                if (!String.IsNullOrEmpty(val))
                    dt.Rows.Add(-1, val, "Name");
                else
                    dt.Rows.Add(-1, null, "Name");
                dgvModel.DataSource = dt;
                this.ScrollToBottom(dgvModel);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

        }

        private void btnModelSave_Click(object sender, EventArgs e)
        {
            try
            {
                //DialogResult result1 = MessageBox.Show("Are you sure to save the change?", "Confirm Message", MessageBoxButtons.YesNo);

                //if (result1 == DialogResult.Yes)
               // {
                    try
                    {
                        this.UpdateData("Model", this.dgvModel);
                        dgvMake_SelectionChanged(this, new EventArgs());
                        this.LoadDataCombo();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        log.Error(ex.Message);
                    }
                //}
            }
            catch (Exception ex)
            {
                
                 MessageBox.Show(ex.Message);
            }
        }

        private void btnModelDelete_Click(object sender, EventArgs e)
        {
            //foreach (DataGridViewRow item in this.dgvModel.SelectedRows)
            //{
            //    dgvModel.Rows.RemoveAt(item.Index);
            //}
            try
            {
                List<DataGridViewRow> list = new List<DataGridViewRow>();
                foreach (DataGridViewRow item in this.dgvModel.SelectedRows)
                {
                    if (!this.isMakeUsed("modeledition", item.Cells["ModelOID"].Value.ToString(), "modelOID"))//check Make is used?
                        dgvModel.Rows.RemoveAt(item.Index);
                    else
                        list.Add(item);
                }
                string name = "";
                if (list.Count > 0)
                {
                    foreach (DataGridViewRow r in list)
                    {
                        name += r.Cells["ModelName"].Value.ToString() + ",";
                    }
                    if (!String.IsNullOrEmpty(name))
                        name = name.Remove(name.LastIndexOf(","));
                    MessageBox.Show(String.Format("Items were used : {0}.", name));

                }
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }
        }

        private void btnYearNew_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)dgvModelYears.DataSource;
                string val = "";
                val = this.dgvMake.SelectedRows[0].Cells["OID"].Value.ToString();
                if (!String.IsNullOrEmpty(val))
                    dt.Rows.Add(-1, val, "ModelYearName");
                else
                    dt.Rows.Add(-1, null, "ModelYearName");

                dgvModelYears.DataSource = dt;
                this.ScrollToBottom(dgvModelYears);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnYearSave_Click(object sender, EventArgs e)
        {
            try
            {
                //DialogResult result1 = MessageBox.Show("Are you sure to save the change?", "Confirm Message", MessageBoxButtons.YesNo);

               // if (result1 == DialogResult.Yes)
               // {
                    try
                    {
                        this.UpdateData("modelyear", this.dgvModelYears);
                        dgvMake_SelectionChanged(this, new EventArgs());
                        this.LoadDataCombo();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        log.Error(ex.Message);
                    }
                //}
            }
            catch (Exception ex)
            {
                
                 MessageBox.Show(ex.Message);
            }
        }

        private void btnYearDelete_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow item in this.dgvModelYears.SelectedRows)
                {
                    dgvModelYears.Rows.RemoveAt(item.Index);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnEditionNew_Click(object sender, EventArgs e)
        {
            if (this.dgvModel.DataSource != null && this.dgvModel.SelectedRows.Count > 0)
            {
                try
                {
                    DataTable dt = new DataTable();
                    if (dgvEdition.DataSource != null)
                        dt = (DataTable)dgvEdition.DataSource;
                    string val = "";
                    if (this.dgvModel.SelectedRows.Count > 0)
                        val = this.dgvModel.SelectedRows[0].Cells["ModelOID"].Value.ToString();
                    if (!String.IsNullOrEmpty(val) && !val.Equals("-1"))
                        dt.Rows.Add(-1, val, "ModeleditionName");
                    else
                        dt.Rows.Add(-1, null, "ModeleditionName");
                    //dt.Rows.Add(-1, null, "ModeleditionName");
                    dgvEdition.DataSource = dt;
                    this.ScrollToBottom(dgvEdition);
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    MessageBox.Show(ex.Message);
                }
            }else 
                MessageBox.Show("Please select a Model or create new one.","Information");
        }

        private void btnEditionSave_Click(object sender, EventArgs e)
        {
            try
            {
               // DialogResult result1 = MessageBox.Show("Are you sure to save the change?", "Confirm Message", MessageBoxButtons.YesNo);

              //  if (result1 == DialogResult.Yes)
              //  {
                    try
                    {
                        this.UpdateData("modeledition", this.dgvEdition);
                        dgvModel_SelectionChanged(this, new EventArgs());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        log.Error(ex.Message);
                    }
               // }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        private void dgvModel_SelectionChanged(object sender, EventArgs e)
        {
            if (this.dgvModel.SelectedRows.Count >0)
            {
                string id = "";

                foreach (DataGridViewRow item in this.dgvModel.SelectedRows)
                {
                    if (id.Equals("") )
                        if (item.Cells["ModelOID"].Value != null)
                            id += item.Cells["ModelOID"].Value.ToString();
                    else
                            if (item.Cells["ModelOID"].Value != null)
                        id += " , " + item.Cells["ModelOID"].Value.ToString();

                }

                //log.Debug("ID----: " + id.ToString());
                if (!String.IsNullOrEmpty(id))
                {
                    //load ModelGrid
                    this.LoadDependentGrids(id, "modeledition", "modelOID", this.dgvEdition);
                }
                else
                {
                    this.dgvEdition.DataSource = null;
                } 
            }
        }

        private void btnGroupNew_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)dgvOptionGroup.DataSource;
                string val = "";
                if (this.dgvMake.SelectedRows.Count > 0)
                    val = this.dgvMake.SelectedRows[0].Cells["OID"].Value.ToString();
                if (!String.IsNullOrEmpty(val) && !val.Equals("-1"))
                    dt.Rows.Add(-1, val, "OptionGroup");
                else
                    dt.Rows.Add(-1, null, "OptionGroup");
                dgvOptionGroup.DataSource = dt;
                this.ScrollToBottom(dgvOptionGroup);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnGroupSave_Click(object sender, EventArgs e)
        {
            try
            {
               // DialogResult result1 = MessageBox.Show("Are you sure to save the change?", "Confirm Message", MessageBoxButtons.YesNo);
               // if (result1 == DialogResult.Yes)
               // {
                    try
                    {
                        this.UpdateData("optiongroup", this.dgvOptionGroup);
                       // dgvModel_SelectionChanged(this, new EventArgs());
                        dgvMake_SelectionChanged(this,new EventArgs());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        log.Error(ex.Message);
                    }
               // }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnEditionDelete_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow item in this.dgvEdition.SelectedRows)
                {
                    dgvEdition.Rows.RemoveAt(item.Index);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnGroupDelete_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow item in this.dgvOptionGroup.SelectedRows)
                {
                    dgvOptionGroup.Rows.RemoveAt(item.Index);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }



        private void ScrollToBottom(DataGridView dg)
        {
            var lastRow = dg.Rows.Count - 1;
            dg.FirstDisplayedScrollingRowIndex = lastRow;
        }




    }
}
